package defineProduct.controller;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.User;

import com.google.gson.Gson;

import defineProduct.model.ItemBean;
/**
 * Servlet implementation class ChooseColorAndSize2
 */
@WebServlet("/ChooseColorAndSize2")
public class ChooseColorAndSize2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ChooseColorAndSize2() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		if(user==null || !user.getAccountType().equals("S")){
			response.sendRedirect("Login.html");
			return;
		}
		ItemBean item = (ItemBean) session.getAttribute("item");
		long colorId = (long) session.getAttribute("colorId");
		if(!item.isFigureUploaded(colorId)){
			response.sendRedirect("/Store/upload/upload.jsp");
			return;
		}
		response.sendRedirect("DefineProduct/ChooseColorAndSize2.jsp");
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		if(user==null || !user.getAccountType().equals("S")){
			response.sendRedirect("Login.html");
			return;
		}
		ItemBean item = (ItemBean) session.getAttribute("item");
		long colorId = Long.parseLong(request.getParameter("colorId"));
		session.setAttribute("colorId", colorId);
		Map<Integer, String> colors = (Map<Integer, String>) session.getAttribute("colors");
		session.setAttribute("color", colors.get(colorId));
		Map<String,String[]> parameterMap = request.getParameterMap();
		String[] sizeIds= parameterMap.get("sizeIds[]");
		String[] counts = parameterMap.get("counts[]");
		for(int i=0; i<sizeIds.length; i++){
			item.addColorSizeCount(colorId, Integer.parseInt(sizeIds[i]), Integer.parseInt(counts[i]));
		}
		Gson gson = new Gson();
//		System.out.println(gson.toJson(item));
//		System.out.println(sizeIds.length);
		session.setAttribute("item", item);
		response.sendRedirect("/Store/upload/upload.jsp");
	}
	

}
